package com.dongdongshop.front.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.cart.pojo.Cart;
import com.dongdongshop.cart.pojo.TbOrderItem;
import com.dongdongshop.cart.service.CartService;
import com.dongdongshop.front.pojo.TbUser;
import com.dongdongshop.front.util.CookieUtils;
import com.dongdongshop_util.Result;
import com.dongdongshop_util.ResultEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CartController {

    Logger logger = LoggerFactory.getLogger(CartController.class);

    @Reference(check = false,timeout = 500000)
    private CartService cartService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("toCart")
    public String toCart(HttpServletRequest request, HttpServletResponse response, Model model){
        //先从cookie中获取购物车数据，获取的是以前添加的购物车数据
        List<Cart> cartList = getCart(request, response);
        double totalFees=0;
        for (Cart cart : cartList) {
            List<TbOrderItem> orderItemList = cart.getOrderItemList();
            for (TbOrderItem orderItem : orderItemList) {
                BigDecimal totalFee = orderItem.getTotalFee();
                totalFees += totalFee.doubleValue();

            }
        }
        model.addAttribute("cartList",cartList);
        model.addAttribute("totalFees",totalFees);
        return "admin/cart";
    }
    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request,HttpServletResponse response){
        //取出登录用户
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser)subject.getPrincipal();
        //从cookie中获取购物车信息
        String cookieValue = CookieUtils.getCookieValue(request, "cartList", "UTF_8");
        //判断cookie中的值是否为空，避免在fastjson转换时出现异常
        /*Optional<String> optional = Optional.ofNullable(cookieValue);
        cookieValue = optional.orElse("[]");*/
        if (StringUtils.isBlank(cookieValue)){
            cookieValue="[]";
        }
        //将json解析为list集合
        List<Cart> carts = JSONObject.parseArray(cookieValue, Cart.class);
        //没登录从cookie里取数据
        if (user == null){
            return carts;
        }else{
            //登录了就从redis里取
            List<Cart> redisCart = cartService.getCartByRedis(user.getUsername());
            if(carts.size() > 0){
                //拼接后的购物车数据
                List<Cart> mergeCartlist = cartService.mergeCartlist(redisCart,carts);
                //拼接完以后cookie里面的数据还在，需要将cookie里的购物车数据清掉
                CookieUtils.deleteCookie(request,response,"cartList");
                //将拼接后的购物车数据添加到redis
                cartService.addCartRedis(user.getUsername(),mergeCartlist);
            }
            return redisCart;
        }
    }

    //往购物车添加数据
    @RequestMapping("addToCart")
    public String addToCart(Long itemId,Integer num,HttpServletRequest request, HttpServletResponse response){
        //从cookie中获取购物车列表
        List<Cart> cartList = getCart(request,response);
        //调用cartService组装购物车
        cartList = cartService.addToCart(cartList,itemId,num);
        //取出登录用户
        Subject subject = SecurityUtils.getSubject();
        TbUser user = (TbUser) subject.getPrincipal();
        //用户没登录就保存到cookie里
        if (user == null){
            //将组装好的购物车数据写入cookie
            CookieUtils.setCookie(request,response,"cartList",JSONObject.toJSONString(cartList),60*60*24*30,"UTF-8");
        }else {
            //用户登录了就保存到redis
            cartService.addCartRedis(user.getUsername(),cartList);
        }
        return "redirect:/cart/toCart";
    }
    //删除
    @ResponseBody
    @RequestMapping("deleteInfo")
    public Result deleteInfo(HttpServletRequest request, HttpServletResponse response){
        try {
            //取出登录用户
            Subject subject = SecurityUtils.getSubject();
            TbUser user = (TbUser)subject.getPrincipal();
            if (user == null){
                //删除cookie中的购物车
                CookieUtils.deleteCookie(request,response,"cartList");
            }else {
                redisTemplate.delete("cartList");
            }
            return Result.perfect(ResultEnum.SUCCESS);
        }catch (Exception e){
            logger.error(String.valueOf(ResultEnum.FAIT),e);
            return Result.perfect(ResultEnum.FAIT);
        }
    }
}
